package com.hcb.tonguetiphealth.widget.citywide;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class CityWideCommitWidget extends GeneralWidget implements OnClickListener {

	private Activity ctx;
	private LinearLayout llBack, llTop;
	private Handler mHandler;
	private boolean commitSuccess;
	private String cityId;
	private User user;
	private EditText etActivity, etAddress , etIntro, etTel;
	private String strActivity, strAddress, strIntro, strTel;
	private Button btCommit;
	private RadioGroup radioGroup;
	private String type = "1";
	private RadioButton rdRes;
	private Dialog waitDialog;
	private RadioGroup radioGroupTop, radioGroupTop2;
	private int topType = 0;
	
	public CityWideCommitWidget(Context context) {
		super(context);
		ctx = (Activity) context;
		inflate(context, R.layout.city_wide_activity, this);
		bindView();
		bindEvent();
		initData();
	}

	private void bindView() {
	 llBack = (LinearLayout)findViewById(R.id.activity_back);
	 etActivity = (EditText)findViewById(R.id.city_wide_activity_edittext);
	 etAddress = (EditText)findViewById(R.id.city_wide_address_edittext);
	 etTel = (EditText)findViewById(R.id.city_wide_tel_edittext);
	 etIntro = (EditText)findViewById(R.id.city_wide_intro_tv);
	 btCommit = (Button)findViewById(R.id.activity_commit_button);
	 radioGroup = (RadioGroup)findViewById(R.id.RadioGroup01);
	 rdRes = (RadioButton)findViewById(R.id.RadioButton_res);
	 rdRes.setChecked(true);
	}
	
	private void bindEvent(){
		llBack.setOnClickListener(this);
		btCommit.setOnClickListener(this);
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在发送请求...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					dismissMessageDialog();
					if (commitSuccess) {
						showMessage(ctx, "请求成功!");
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						ctx.setContentView(new CityWideWidget(ctx));
					}else {
						showMessage(ctx, "请求失败，请稍后重试");
					}
					break;
				 
				case MessageWhat.NETWORK_FAILD:
					try {
					  dismissMessageDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					//Toast.makeText(ctx,  "网络有点不给力哦", Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					break;
				}
			}
		};
		
		
		  /* 设置事件监听  */  
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {  
            @Override  
            public void onCheckedChanged(RadioGroup group, int checkedId)  
            {  
                switch (checkedId) {
					case R.id.RadioButton_res:
						type = "1";//活动类型为商家
						break;
					case R.id.RadioButton_person:
						type = "2";//活动类型为个人
						break;
					default:
						break;
				}
            }  
        });

	}

	private void initData(){
		SharedPreferences preferences = ctx.getSharedPreferences(Global.CITYID,
				0);
		cityId = preferences.getString(Global.CITYID, Global.defaultCityId);
		user = Global.user;
	}
	
	private void commitData(){
		commitSuccess = false;
		user = Global.user;
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run(){
				List<NameValuePair>params = new ArrayList<NameValuePair>();
				System.out.println("type:----------"+type);
				params.add(new BasicNameValuePair("cityId", cityId));
				params.add(new BasicNameValuePair("userId", user.getUserId()));
				params.add(new BasicNameValuePair("activity", strActivity));
				params.add(new BasicNameValuePair("address", strAddress));
				params.add(new BasicNameValuePair("tel", strTel));
				params.add(new BasicNameValuePair("intro", strIntro));
				params.add(new BasicNameValuePair("activityType", type));
				params.add(new BasicNameValuePair("topType", topType +"")); //0: 非置顶 1：一天，2 ：一周
				String respone = HttpUtils.Post(Global.getServletactivitycommit(), params);
				if (Global.DEBUG) {
					System.out.println("提交活动返回信息:"+respone);
				}
				if (respone!=null) {
					try {
						JSONObject jsonObject = new JSONObject(respone);
						String strReturn = jsonObject.getString("return");
						if ("true".equals(strReturn)) {
							commitSuccess = true;
						}else {
							commitSuccess = false;
						}
						System.out.println("msg : "+jsonObject.getString("msg"));
						mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						commitSuccess = false;
						e.printStackTrace();
						mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
					}
				}else {
					commitSuccess = false;
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
			}
		}.start();
	}
	
	@Override
	public void notifyAdapter() {

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.activity_back:
			ctx.setContentView(new CityWideWidget(ctx));
			break;
		case R.id.activity_commit_button:
			strActivity = etActivity.getText().toString();
			strAddress = etAddress.getText().toString();
			strTel = etTel.getText().toString();
			strIntro = etIntro.getText().toString();
			if (strActivity == null || "".equals(strActivity)) {
				showMessage(ctx, "活动名不能为空！");
				return;
			}
			if (strAddress == null || "".equals(strAddress)) {
				showMessage(ctx, "活动地点不能为空！");
				return;
			}
			if (strTel == null || "".equals(strTel)) {
				showMessage(ctx, "报名电话不能为空！");
				return;
			}
			if (Global.user == null) {
				login();
			} else {
				if(type.equals("1")) {
					showTopDialog();
				} else {
					commitData();
				}
			}
			break;
		default:
			break;
		}
	}

	protected void showTopDialog() {
    	waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
	    waitDialog.setContentView(R.layout.activity_top_dialog);
	//    waitDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
	//     waitDialog.setCancelable(false);
	    
	    //设置窗口里控件的透明度
	    Window window = waitDialog.getWindow();
	    WindowManager.LayoutParams wl = window.getAttributes();
	    wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
	    wl.alpha = 0.95f;			//０.０全透明．１.０不透明．
	    window.setAttributes(wl);
	    llTop = (LinearLayout)waitDialog.findViewById(R.id.activity_top_dialog_linearlayout);
	    radioGroupTop = (RadioGroup)waitDialog.findViewById(R.id.activity_top_dialog_rg);
	    radioGroupTop2 = (RadioGroup)waitDialog.findViewById(R.id.activity_top_dialog_rg2);
	    
	    radioGroupTop.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch(checkedId) {
				case R.id.activity_top_dialog_rb_no:
					llTop.setVisibility(LinearLayout.GONE);
					break;
				case R.id.activity_top_dialog_rb_top:
					llTop.setVisibility(LinearLayout.VISIBLE);
					break;
				}
			}
		});
	    
    	Button cancel0 = (Button)waitDialog.findViewById(R.id.activity_top_dialog_cancel0_bt);
    	Button cancel = (Button)waitDialog.findViewById(R.id.activity_top_dialog_cancel_bt);
    	Button ok = (Button)waitDialog.findViewById(R.id.activity_top_dialog_ok_bt);
    	cancel0.setOnClickListener(listner);
    	cancel.setOnClickListener(listner);
    	ok.setOnClickListener(listner);
    	
    	waitDialog.show();
	}
	OnClickListener listner = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch(v.getId()) {
			case R.id.activity_top_dialog_cancel0_bt:
				waitDialog.dismiss();
				break;
			case R.id.activity_top_dialog_cancel_bt:
				waitDialog.dismiss();
				break;
			case R.id.activity_top_dialog_ok_bt:
				topType = 0;
				switch(radioGroupTop.getCheckedRadioButtonId()) {
				case R.id.activity_top_dialog_rb_no:
					topType = 0;
					break;
				case R.id.activity_top_dialog_rb_top:
					switch(radioGroupTop2.getCheckedRadioButtonId()) {
					case R.id.activity_top_dialog_rb_day:
						topType = 1;
						break;
					case R.id.activity_top_dialog_rb_week:
						topType = 2;
						break;
					}
					break;
				}
				waitDialog.dismiss();
				commitData();
				break;
			}
		}
	};
	
}
